package com.keruyun.base.lock;

import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * Created by shynin on 18-4-25.
 */
public class BootRedisLock implements Lock {
    private AbstractQueuedSynchronizer aqs;

    public BootRedisLock(String lockKey, RedisTemplate redisTemplate) {
        aqs = new SynchronizedQueueRedis(lockKey, redisTemplate);
    }

    @Override
    public void lock() {
        aqs.acquire(1);
        System.out.println("线程: " + Thread.currentThread().toString() + " 获取了锁");
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {
        aqs.acquireInterruptibly(1);
    }

    @Override
    public boolean tryLock() {
        try {
            return aqs.tryAcquireNanos(1, TimeUnit.MINUTES.toSeconds(5L));
        } catch (Exception e) {
            return false;
        }

    }

    @Override
    public boolean tryLock(long l, TimeUnit timeUnit) throws InterruptedException {
        return aqs.tryAcquireNanos(1, TimeUnit.MINUTES.toSeconds(5L));
    }

    @Override
    public void unlock() {
        System.out.println("线程: " + Thread.currentThread().toString() + " 释放了锁");
        aqs.release(1);
    }

    @Override
    public Condition newCondition() {
        return aqs.new ConditionObject();
    }
}
